// pages/biz/mine/mine.js
import Serv from './mineServ';
// import wxCodeServ from '../../housePoster/housePosterServ.js';
// import Config from '../../../utils/config2.js'
import Config from '../../../utils/config2.js'
import util from '../../../utils/util.js'
import util2 from '../../../utils/util2.js'

// let cf = require("/config.js");
var regeneratorRuntime = require("../../../lib/js/runtime-module.js")
var cf = require("../../../config")
const app = getApp();
const setScrollHeight = app.setScrollHeight
Page({

  /**
   * 页面的初始数据
   */
  data: {
    eId:'',
    msgNum:0,
    userDetail: {},
    userInfo: {},
    isLogin: -1,
    roleName: '',
    bgNum:'',
    userbg: [`${cf.config.posterOssHost}poster/getMoney1.png`, `${Config.ossHost}images/getMoney2.jpg`, `${Config.ossHost}images/getMoney3.jpg`],
    isImgLoaded:false,
    preLoadImg:[],
    isAgent:false,
    isSales: false, //是否是销售员
    appointmentTotal:0,
    myCardTotal:0,
    authName:wx.getStorageSync('authName')||''
  },
  //获取名片列表
  queryCardList() {
    var ctx = this;
   
    wx.request({
      url:`${cf.config.pageDomain}applet/mobile/visitcard/memberrelation/findByMemberOpenId`,
      data: {
        cusmallToken:  wx.getStorageSync('cusmallToken'),
        start: 0,
        limit: 10
      },
      header: {
        'content-type': 'application/json',
        'token':wx.getStorageSync('authName')
      },
      success: function(res) {
        var data = res.data;
        if(data.msg){
          ctx.setData({
            myCardTotal:data.model.total||0
          });
        }
         
      }
    })
  },
  // 获取用户信息
  async getUserInfo(params) {
    let { employee,isAgent } = this.data;
    let resule = await Serv.getUserInfo(params)
    let userInfo = wx.getStorageSync('userInfo')
    // console.log(res,'res-------------------')
    // resule.data.headImgUrl = res.avatarUrl
    if (resule.success) { // 用户信息获取成功
      if(userInfo){
        resule.data.headImgUrl= userInfo.avatarUrl
        resule.data.nickName = userInfo.nickName
      }
      if(employee&&resule.data){
        resule.data.headImgUrl= employee.headPic
        resule.data.nickName = employee.nickName
      }
      if(resule.data.roleList&&resule.data.roleList.length>0){
        let roleList = resule.data.roleList;
        let roleIndex = roleList.findIndex((item)=>{
          let reg = RegExp(/经纪人/);
          return item.name&&item.name.match(reg)
        });
        if(roleIndex>=0){
          isAgent=true
        }
      }
      this.setData({ userInfo: resule.data,isAgent })
	    wx.setStorageSync(Config.userName, resule.data.name)
    }
  },
  //获取客户详情
  async getUserDetail(params) {
    let result = await Serv.getUserDetail(params) // 请求数据
    if (result.success) { // 数据请求成功
      this.setData({ userDetail: result.data })
    }
  },
  //跳转升级经纪人页面
  toAgentPoster(){
    wx.navigateTo({
      url:'/subPackages2/pages/agentPoster/agentPoster'
    });
  },
  //获取角色名称
  async getRoleName() {
    let result = await Serv.getRoleName() // 请求数据
    if (result.success) { // 数据请求成功
      wx.setStorageSync(Config.roleName , result.data);
      this.setData({ roleName: result.data })
    }
  },
  async appointment(){
    let query = {
      pageNum:1,
      pageSize:10
    }
    let result = await Serv.getAppointment(query) //请求数据
    this.setData({
      appointmentTotal:result.total||0
    })
    // console.log(result)
    
  },
  //分享名片
  linkposter:function (){
    let employee = wx.getStorageSync('employee')
    // var ctx = this;
    wx.navigateTo({
      url: '/pages/canvas/index?eId=' + employee.id,
    });
  },
  /** 跳转佣金页面 **/
  commissionLink: function () {
    let {isLogin} = this.data
    wx.navigateTo({
      url: isLogin == 0 ? '/pages/biz/login/login':'/subPackages2/pages/commission/commission' 
    })
  },
  /** 跳转优惠券列表页面 **/
  couponsLink: function () {
    let { isLogin } = this.data
    wx.navigateTo({ url: isLogin == 0 ? '/subPackages/pages/login/login' : '/subPackages2/pages/my/myCoupons/couponsList/couponsList' })
  },
  intergralLink: function () {
    let { isLogin } = this.data
    wx.navigateTo({ url: isLogin == 0 ? '/subPackages/pages/login/login' : '/pages/load/load' })
  },
  intergral: function () {
    let { isLogin } = this.data // 是否登录
    wx.navigateTo({ url: isLogin == 0 ? '/subPackages/pages/login/login' :'/subPackages/pages/Integral/Integral' })
  },
  // 功能不支持提示
  nonSupport: function () {
    wx.showToast({
      title: '敬请期待',
      icon: 'none'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */ 
  onLoad: function (options) {
    app.getEmployeeInfo(); 
    console.log(this.data.userbg)
    this.setData({
      eId: options.eId || wx.getStorageSync("eId") || ""
    })
  },
    // 调整到名片后台
    toSales() {
      wx.navigateTo({
        url: '/pages/sales/me/me',
      })
    },
  // 链接跳转
  linkJump: function (e) {
    let { isLogin, preLoadImg} = this.data // 是否登录
    if (isLogin==0) { // 未登录
      wx.navigateTo({ url:'/subPackages/pages/login/login'})
    } else if (isLogin==1) { // 已登录
      // if(this.data.eId){
      //   util.addBehaviorTrail(this.data.eId, 55,);
      // }
      // debugger
      wx.setStorageSync('preLoadImg', preLoadImg)
      let url = e.currentTarget.dataset.url; // 跳转url
      // wx.navigateTo({ url:url})
      //以下代码跳转到美的官网，等需要https域名，等业务确认是否能做后开启
      let url2 = `https:\/\/www.mideadc.com`
      wx.navigateTo({
        url: `${url}?webUrl=${url2}`
      })
    }
  },
  // setScrollHeight(id){
  //   let promise = new Promise((resolve,reject)=>{
  //     let scrollHeight = 0
  //     wx.getSystemInfo({
  //       success: function (res) {
  //         let windowHeight = res.windowHeight
  //         console.log(windowHeight)
  //         const query = wx.createSelectorQuery()
  //         query.select(id).boundingClientRect()
  //         query.selectViewport().scrollOffset()
  //         query.exec(function (res) {
  //           scrollHeight = windowHeight - res[0].height
  //           if(scrollHeight){
  //             resolve(scrollHeight)
  //           }
  //         })
  //       }
  //     })
  //   })
  //   return promise;
  // },
  /**
   * 设置
   */
  setWebClick() {//entrance=1客户端
    wx.navigateTo({
      url: `/subPackages2/pages/setWeb/setWeb?entrance=1`
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },
   onBills(){
     wx.navigateTo({
       url:'/subPackages3/pages/myOrderList/myOrderList'
     });
   },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    setScrollHeight('#navbar').then(res=>that.setData({scrollHeight:res}))
    let { userbg, preLoadImg} = this.data
    app.getEmployeeInfo().then(()=>{
      let employee = wx.getStorageSync('employee');
      if(employee){
        that.setData({
          isSales:employee?employee.isSales:false,
          employee:employee
        });
      }
    })
    if (preLoadImg.length <= 3){
      this.setData({
        isImgLoaded:false
      })
    }
    let wxSession = wx.getStorageSync("authName") // token是否存在
     let isLogin = -1
    if (wxSession == "" || wxSession == null || wxSession == undefined) {
      // wx.navigateTo({ url: '/pages/biz/login/login' })
      isLogin = 0
    }else {
      isLogin = 1
    }
    this.setData({isLogin:isLogin})
    if (isLogin==1) {
      // 已登录
      let params = {
        accountId: ''
      }
      this.queryCardList();
      this.getUserDetail(params)
      // let token = wx.getStorageSync(Config.authName) // 获取缓存中的token
      let userparams = {
        // accountId: '123',
        appId: '1' // 暂时写1
        // token: token
      }
      this.getUserInfo(userparams) // 获取用户信息
      this.getRoleName() // 获取角色名称
      this.appointment() //获取预约看房数据
      if (preLoadImg.length <= 3) {
        util2.getWxacode({}, 'index', 1).then((res) => {
          // debugger
          //console.log(res)
          res && userbg.push(res)
          util2.imgPreLoad(userbg, (preLoadImg) => {
            this.setData({
              preLoadImg,
              isImgLoaded: true
            })
          })
        })

      }
    } else { // 未登录
      let userDetail = {
        commission: 0,
        coupons: 0,
        integral: 0
      }
      this.setData({ userDetail: userDetail, roleName:'',msgNum:app.globalData.messageCount,isImgLoaded:true })
    }
   
  },
  //专属海报
  // sharePoster() {
  //   let bgNum = parseInt(3 * Math.random());
  //   let { preLoadImg, isLogin} = this.data
  //   if(isLogin==1){
  //     wx.setStorageSync('preLoadImg', preLoadImg)
  //   }
  //   setTimeout(()=>{
  //     wx.navigateTo({
  //       url: `/pages/biz/housePoster/housePoster?pageName=index&num=${bgNum}`
  //     })
  //   },200)
  // }, 
  // 分享显示
  // shareAction: function () {
  //   // wx.showShareMenu({
  //   //   withShareTicket: true
  //   // });
  // },
  onShareAppMessage: function (res) {
    console.log(res.target)
    return {
      title: '金科神器',
      path: '/pages/index/index'
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
})